/* 
 * Copyright 2010 Ziya Guven Koylu, Ozge Koylu
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at 
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */
package com.koylu.caffein.query.order;

import java.util.Map;

import com.koylu.caffein.model.caffein.CaffeinConfig;
import com.koylu.caffein.model.clazz.Clazz;
import com.koylu.caffein.model.clazz.Column;

public class Order {

	private Column column;
	private String alias;
	private String path;
	private String type;
	private String columnAlias;
	private StringBuffer query = null;
	
	public Order() {}
	
	public Order(String alias, String path, String type) {
		this.alias = alias;
		this.path = path;
		this.type = type;
	}
	
	public Order(String columnAlias, String type) {
		this.columnAlias = columnAlias;
		this.type = type;
	}

	public String getAlias() {
		return alias;
	}

	public void setAlias(String alias) {
		this.alias = alias;
	}

	public String getPath() {
		return path;
	}

	public void setPath(String path) {
		this.path = path;
	}

	public String getType() {
		return type;
	}

	public void setType(String type) {
		this.type = type;
	}
	
	public String getColumnAlias() {
		return columnAlias;
	}
	
	public void setColumnAlias(String columnAlias) {
		this.columnAlias = columnAlias;
	}

	public StringBuffer toQuery(CaffeinConfig caffeinConfig, Map<String, Clazz> aliasMap) throws Exception {
		if(query == null){
			if(columnAlias == null){
				if (column == null) {
					if(aliasMap.containsKey(alias)){
						column = aliasMap.get(alias).pathToColumn(caffeinConfig, path);
						if(column == null){
							throw new RuntimeException("invalid clazz path:"+path);
						}
					}else{
						throw new RuntimeException("invalid clazz alias:"+alias);
					}
				}
				query = new StringBuffer(alias).append(".").append(column.getColumn()).append(" ").append(type);
			}else{
				query = new StringBuffer(columnAlias).append(" ").append(type);				
			}
		}
		return query;
	}
	
	public static Order asc(String alias, String path) {
		return new Order(alias, path, "ASC");
	}
	
	public static Order asc(String columnAlias) {
		return new Order(columnAlias, "ASC");
	}

	public static Order desc(String alias, String path) {
		return new Order(alias, path, "DESC");
	}
	
	public static Order desc(String columnAlias) {
		return new Order(columnAlias, "DESC");
	}
}